<template>
  <div class="theme">
    <Row class="margin-top-10">
      <p class="find" style="margin-bottom: 20px">
        <b class="theme__title">书籍推荐栏目管理</b>
        <Input
          class="theme__input"
          v-model="searchStr"
          placeholder="试试搜索主题关键字"
          clearable
        />
        <Button type="primary" @click="findData">查询</Button>
        <Button class="right" type="success" @click="handleAdd">新增</Button>
      </p>
      <Table :columns="columns" :data="datas" :loading="loading"></Table>
      <Page
        class="pager"
        v-if="total > 0"
        :total="total"
        show-total
        show-elevator
        show-sizer
        :page-size="limit"
        @on-change="handlePageChange"
        @on-page-size-change="handlePageSizeChange"
      />
      <!-- 新增修改弹窗 -->
      <Modal
        class="common-dialog"
        v-model="showModal"
        :title="modalTitle"
        :loading="modalLoading"
        width="600"
        :mask-closable="false"
      >
        <Form
          ref="modalForm"
          :model="modalData"
          :rules="modalRule"
          :label-width="100"
        >
          <FormItem prop="name" label="主题名称" :error="modalError.name">
            <Input v-model="modalData.name" placeholder="请输入主题名称" />
          </FormItem>
          <FormItem
            prop="background"
            label="布局方式"
            :error="modalError.layout"
          >
            <Select
              v-model="modalData.layout"
              placeholder="请选择布局方式"
              style="width: 200px"
            >
              <Option :value="1">4书横向展示</Option>
              <Option :value="2">5书(一主四次)展示</Option>
              <Option :value="3">6书纵向展示</Option>
            </Select>
            <div
              v-if="modalData.layout === 1"
              class="common-dialog__tips-img"
              style="
                background-image: url('https://picture-1256514897.file.myqcloud.com/book/images/layout1.png');
              "
            />
            <div
              v-else-if="modalData.layout === 2"
              class="common-dialog__tips-img"
              style="
                background-image: url('https://picture-1256514897.file.myqcloud.com/book/images/layout2.png');
              "
            />
            <div
              v-else-if="modalData.layout === 3"
              class="common-dialog__tips-img"
              style="
                background-image: url('https://picture-1256514897.file.myqcloud.com/book/images/layout3.png');
              "
            />
          </FormItem>
          <FormItem prop="des" label="描述" :error="modalError.des">
            <Input
              v-model="modalData.des"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 6 }"
              placeholder="输入图片描述，将会展示在图片下方"
              style="font-size: 12px"
            />
          </FormItem>
          <FormItem prop="show" label="是否展示" :error="modalError.show">
            <i-switch v-model="modalData.show" />
          </FormItem>
          <FormItem prop="show" label="是否可刷新" :error="modalError.flush">
            <i-switch v-model="modalData.flush" />
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="handleModalCancel">取消</Button>
          <Button type="primary" @click="handleModalConfrim">确认</Button>
        </div>
      </Modal>
    </Row>
  </div>
</template>

<script>
import http from "@/utils/http";
import moment from "moment";

function layoutWay(layout) {
  if (layout === 1) {
    return "4书横向展示";
  } else if (layout === 2) {
    return "5书(一主四次)展示";
  } else if (layout === 3) {
    return "6书纵向展示";
  } else {
    return "";
  }
}

// 默认数据
const DEFAULT_DATA = {
  name: "",
  layout: "",
  des: "",
  show: true,
  flush: true,
};
// 模块名称
const NAME = "主题";
const MODULE = "theme";
const RULE = {
  name: [{ required: true, message: "请输入主题名称", trigger: "input" }],
  layout: [{ required: true, message: "请选择主题布局", trigger: "select" }],
  url: [{ required: true, message: "请填写跳转地址", trigger: "change" }],
  des: [{ required: true, message: "请输入主题的描述", trigger: "input" }],
};

export default {
  name: MODULE,

  data() {
    return {
      loading: true,
      searchStr: "",
      datas: [],
      total: 0,
      page: 1,
      limit: 10,
      columns: [
        {
          title: "序号",
          key: "index",
          width: 80,
          align: "center",
        },
        {
          title: "主题名称",
          align: "center",
          key: "name",
          width: 150,
          ellipsis: true,
        },
        {
          title: "描述信息",
          align: "center",
          key: "des",
          render: (h, params) => {
            return <span class="two-row-ellipsis">{params.row.des}</span>;
          },
        },
        {
          title: "书籍数量",
          align: "center",
          key: "num",
          width: 100,
          render: (h, params) => {
            return <b>{params.row.book_num || 0}本</b>;
          },
        },
        {
          title: "布局方式",
          align: "center",
          key: "layout",
          render: (h, params) => {
            return <Tag>{layoutWay(params.row.layout)}</Tag>;
          },
        },
        {
          title: "是否可刷新",
          align: "center",
          key: "flush",
          width: 120,
          render: (h, params) => {
            return <i-switch size="small" value={params.row.flush} disabled />;
          },
        },
        {
          title: "是否展示",
          align: "center",
          key: "show",
          width: 110,
          render: (h, params) => {
            return <i-switch size="small" value={params.row.flush} disabled />;
          },
        },
        {
          title: "创建时间",
          align: "center",
          width: 110,
          key: "create_time",
          render: (h, params) => {
            return (
              <span>
                {moment(params.row.create_time).format("YYYY/MM/DD HH:MM:SS")}
              </span>
            );
          },
        },
        {
          title: "操作",
          align: "center",
          width: 260,
          key: "handle",
          render: (h, params) => {
            return (
              <div>
                <Button
                  type="dashed"
                  size="small"
                  class="text-red"
                  onClick={() => this.handleTop(params.row)}
                >
                  置顶
                </Button>
                <Button
                  type="dashed"
                  size="small"
                  class="text-red"
                  onClick={() => this.handleUpdate(params.row)}
                >
                  修改
                </Button>
                <Button
                  type="primary"
                  size="small"
                  class="text-red"
                  onClick={() => this.handleEditBook(params.row)}
                >
                  编辑书籍
                </Button>
                <Button
                  type="error"
                  size="small"
                  class="text-red"
                  onClick={() => this.handleDelete(params.row)}
                >
                  删除
                </Button>
              </div>
            );
          },
        },
      ],
      showModal: false, // 控制modal的显隐
      modalLoading: false, // 点击modal确定按钮是否显示loading
      modalTitle: "", // modal标题
      isAddOrUpdate: "", // 是新增弹窗或者更新弹窗
      currentId: "", // 当前正在修改的商品Id
      modalData: { ...DEFAULT_DATA },
      modalRule: RULE,
      modalError: {},
    };
  },
  methods: {
    // 获取数据
    getData() {
      this.loading = true;
      http({
        method: "GET",
        url: `/api/admin/${MODULE}`,
        params: {
          page: this.page,
          limit: this.limit,
          search: this.searchStr,
        },
        operation: `获取${NAME}`,
      }).then((res) => {
        this.loading = false;
        if (res.data && res.ok) {
          this.datas = res.data.list.map((item, index) => {
            item.index = (this.page - 1) * this.limit + index + 1;
            return item;
          });
          this.total = res.data.total;
        }
      });
    },
    // 查找数据
    findData() {
      this.limit = 10;
      this.page = 1;
      this.total = 0;
      this.getData();
    },
    // 打开新增弹窗
    handleAdd() {
      this.modalData = { ...DEFAULT_DATA };
      this.showModal = true;
      this.modalTitle = `新增${NAME}`;
      this.isAddOrUpdate = "add";
    },
    // 置顶数据
    handleTop(item) {
      http({
        method: "POST",
        url: `/api/admin/${MODULE}/exchange`,
        data: {
          id: item._id,
          from: item.priority,
          to: 1,
        },
        operation: `置顶${NAME}`,
      }).then((res) => {
        if (res.data && res.ok) {
          this.$Message.success(`置顶${NAME}成功`);
          this.getData();
        }
      });
    },
    // 打开修改弹窗
    handleUpdate(item) {
      Object.keys(DEFAULT_DATA).forEach((key) => {
        this.modalData[key] = item[key];
      });
      this.showModal = true;
      this.modalTitle = `修改${NAME}`;
      this.isAddOrUpdate = "update";
      this.currentId = item._id;
    },
    // 编辑主题书籍
    handleEditBook(item) {
      this.$router.push({
        path: `/index-manage/theme/${item._id}`,
      });
    },
    // 删除数据
    handleDelete(item) {
      this.$Modal.confirm({
        title: "温馨提示",
        content: `确定要删除此${NAME}？`,
        onOk: () => {
          http({
            method: "DELETE",
            url: `/api/admin/${MODULE}/${item._id}`,
            operation: `删除${NAME}`,
          }).then((res) => {
            if (res.data && res.ok) {
              // 更新datas
              this.showModal = false;
              this.$Message.success(`删除${NAME}成功`);
              this.getData();
            }
          });
        },
        onCancel: () => {},
      });
    },
    // 自定义校验
    selfValidator(data) {
      return true;
    },
    // 取消弹窗loading
    closeModalLoading() {
      this.modalLoading = false;
      // 避免校验完直接关闭弹窗
      this.$nextTick(() => {
        this.modalLoading = true;
        this.showModal = true;
      });
    },
    handleModalConfrim() {
      // 合法性校验
      this.$refs["modalForm"].validate((valid) => {
        if (valid) {
          // 如果全部校验通过，发送POST请求
          if (this.selfValidator(this.modalData)) {
            if (this.isAddOrUpdate === "add") {
              this.modalLoading = true;
              http({
                method: "POST",
                url: `/api/admin/${MODULE}`,
                data: this.modalData,
                operation: `新增${NAME}`,
              })
                .then((res) => {
                  this.modalLoading = false;
                  if (res.data && res.ok) {
                    this.showModal = false;
                    this.$Message.success(`新增${NAME}成功`);
                    this.getData();
                  }
                })
                .catch((err) => {
                  this.modalLoading = false;
                  this.$Message.error(`新增${NAME}失败, ${err.toString}`);
                });
            } else if (this.isAddOrUpdate === "update") {
              this.modalLoading = true;
              http({
                method: "PUT",
                url: `/api/admin/${MODULE}/${this.currentId}`,
                data: this.modalData,
                operation: `修改${NAME}`,
              })
                .then((res) => {
                  this.modalLoading = false;
                  if (res.data && res.ok) {
                    this.showModal = false;
                    this.$Message.success(`修改${NAME}成功`);
                    this.getData();
                  }
                })
                .catch((err) => {
                  this.modalLoading = false;
                  this.$Message.error(`新增${NAME}失败, ${err.toString}`);
                });
            }
          }
        }
      });
    },
    handleModalCancel() {
      this.$refs["modalForm"].resetFields();
      this.showModal = false;
    },
    // 点击分页
    handlePageChange(val) {
      this.page = val;
      this.getData();
    },
    handlePageSizeChange(size) {
      this.limit = size;
      this.getData();
    },
  },
  created() {
    this.getData();
  },
};
</script>

<style lang="scss">
.theme {
  &__title {
    font-size: 16px;
  }

  &__input {
    display: inline-block;
    width: 200px;
    margin-left: 20px;
    margin-right: 20px;
  }

  .right {
    float: right;
  }
  .add-icon {
    float: right;
  }
  .overflow-text {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .ivu-tooltip-inner {
    max-width: inherit;
  }
  .change-btn {
    margin-right: 15px;
  }
  .pager {
    text-align: right;
    margin-top: 30px;
  }
}
</style>
